package com.browsesoft.oa;

import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.baseadapter.HTMLBasicTableModelAdapter;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.resource.LicensePolicyTool;
import com.browsesoft.resource.Resource;

/**
 * 权限表格model,将权限进行细分到是否可查看,修改,删除等
 */
public class BasicRightTableModel extends HTMLBasicTableModelAdapter {
	/**
	 * 父资源
	 */
	protected Resource resource = null;

	/**
	 * 权限类型
	 */
	private LinkedList rightsType = new LinkedList();

	/**
	 * 初始化
	 * 
	 * @param request
	 *            客户端请求
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
		// 得到要看的资源
		this.resource = (Resource) EntityManager.getInstance().getObject(
				this.parentID);
		this.rightsType.addAll(LicensePolicyTool.getRightType(this.loginUser,
				this.resource));
	}

	/**
	 * 修改单元值
	 * 
	 * @param td
	 *            单元格
	 * @param doc
	 *            doc文档
	 * @param row
	 *            行数
	 * @param col
	 *            列数
	 */
	public void modifyCellValue(Element td, Document doc, int row, int col) {
		try {
			com.browsesoft.Entity entity = (com.browsesoft.Entity) this
					.getOneRow(row);
			if (col >= this.TDPosition.x && col <= this.TDPosition.y) {
				this.replace(entity, col - this.TDPosition.x, td, doc);
			}
			// 否则
			else {
				String righttype = td.getAttribute("righttype");
				if (this.rightsType.contains(righttype)) {
					// 替换td中属性值
					this.replaceTD(td, entity);
				}
				// 否则
				else {
					// 移走
					ExtendElement.removeChilds(td);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @param c
	 *            基本组件
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
		// 得到表格外带权限的按钮
		LinkedList ls = ExtendElement.findElements(this.component.getElement(),
				"rightbutton", "rightbutton");
		if (ls.size() > 0) {
			// 对于每一个
			Iterator iter = ls.iterator();
			while (iter.hasNext()) {
				Element rb = (Element) iter.next();
				// 得到权限类型
				String righttype = rb.getAttribute("righttype");
				// 如果没有权限
				if (!this.rightsType.contains(righttype)) {
					// 移走
					rb.getParentNode().removeChild(rb);
				}
			}
		}
		ls = ExtendElement.findElements(this.component.getElement(),
				"allcheck", "allcheck");
		if (ls.size() > 0) {
			Element allcheck = (Element) ls.get(0);
			// 得到权限类型
			String righttype = allcheck.getAttribute("righttype");
			// 如果没有权限
			if (!this.rightsType.contains(righttype)) {
				// 移走
				ExtendElement.removeChilds(allcheck);
			}
		}
	}
}